#!/bin/bash

# 获取原始用户的用户名和家目录
get_original_user_info() {
    original_username="$SUDO_USER"

    user_info=$(getent passwd "$original_username")

    # 提取家目录信息
    user_home=$(echo "$user_info" | cut -d: -f6)

    # 返回用户名和家目录
    echo "$original_username:$user_home"
}

# 检查是否使用 sudo 运行
if [ -n "$SUDO_USER" ]; then
    # 如果使用 sudo，则获取原始用户的用户名和家目录
    original_user_info=$(get_original_user_info)

    # 分割用户名和家目录
    IFS=':' read -r original_username original_user_home <<< "$original_user_info"

    # 输出结果
else
    # 如果没有使用 sudo，则直接使用 $USER 和 $HOME
    original_username=$USER
    original_user_home=$HOME
fi

conn() {
    cp -r $original_user_home/WORKDIR/connectivity/build/linux/x64/release/bundle/lib ./opt/starkylin_connectivity/
    cp -r $original_user_home/WORKDIR/connectivity/build/linux/x64/release/bundle/data ./opt/starkylin_connectivity/
    cp $original_user_home/WORKDIR/connectivity/build/linux/x64/release/bundle/connectivity ./opt/starkylin_connectivity/connectivity
    cp $original_user_home/WORKDIR/connectivity/build/linux/x64/release/bundle/starkylin_connectivity_service ./opt/starkylin_connectivity/
    cp $original_user_home/WORKDIR/connectivity/build/linux/x64/release/bundle/starkylin_connectivity.service ./etc/systemd/system/
    cp ./postinst_connecitvity ./DEBIAN/postinst
}

test() {
    cp $original_user_home/TEST/qt-test/build/daemon_test ./opt/starkylin_connectivity/
    cp $original_user_home/TEST/qt-test/test.service ./etc/systemd/system/
    cp ./postinst_test ./DEBIAN/postinst
}

createDeb() {
    dpkg-deb -b . a.deb
    dpkg -i a.deb
}

ACTION="$1"
SERVICE_NAME=""

case "$ACTION" in
    conn)
        conn
        SERVICE_NAME="starkylin_connectivity.service"
        ;;
    test)
        test
        SERVICE_NAME="test.service"
        ;;
    *)
        echo "Usage:  <conn|test>"
        exit 1
        ;;
esac

createDeb
# systemctl status $SERVICE_NAME
